﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OPCHDAAutomation;
using OPCAutomation;
using System.Net;
using MySql.Data.MySqlClient;
using System.IO;

namespace opc自写
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        OPCServer opcserver;
        OPCItem oPCItem;                              //实例化
        OPCItems oPCItems;
        OPCBrowser oPCBrowser;
        OPCGroup oPCGroup;
        OPCGroups oPCGroups;
        IPHostEntry iPHostEntry=new IPHostEntry();
        string strHostname = null;
        Object OPCServerlist;
        List<ClassOpcdata> OPCValueList = new List<ClassOpcdata>();
        List<OPCItem> opcitemslist = new List<OPCItem>();
        int count = 0;
        int serverhandle = 0;

        MySqlConnection conn;
        DataSet ds;
        MySqlDataAdapter sda;
        string strHostIP = "";
        string strHostName = "";





        private bool ConnectRemoteServer(string remoteServerIP, string remoteServerName)
        {
            try
            {
                opcserver.Connect(remoteServerName, remoteServerIP);
          
                
            }
            catch (Exception err)
            {
                MessageBox.Show("连接远程服务器出现错误：" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.buttonrefresh_Click(buttonrefresh,null);
            this.dataGridViewvalue.AutoGenerateColumns = false;
            //数据库
            conn = new MySqlConnection("server = localhost; user id = root; password = 103098; database = wzw");
            MySqlCommand cmd = new MySqlCommand("select * from opc", conn);
            sda = new MySqlDataAdapter();
            sda.SelectCommand = cmd;
            ds = new DataSet();
            sda.Fill(ds, "cs");
        }

        private void buttonrefresh_Click(object sender, EventArgs e)       //刷新显示服务器
        {

         


            try
            {
                this.comboBox1server.Items.Clear();
                if (textBox1.Text == null)
                {
                    iPHostEntry = Dns.GetHostEntry(Environment.MachineName);

                }
                else iPHostEntry = Dns.GetHostEntry(textBox1.Text);
                strHostname = iPHostEntry.HostName;
                opcserver = new OPCServer();
                OPCServerlist = opcserver.GetOPCServers(strHostname);
                foreach (var item in (Array)OPCServerlist)
                {
                    if (!this.comboBox1server.Items.Contains(item.ToString()))
                    {
                        this.comboBox1server.Items.Add(item.ToString());
                    }
                }
            }
            catch
            {
                MessageBox.Show("未找到服务器！！！");
            }
        }

        private void buttonconnect_Click(object sender, EventArgs e)
        {
            try
            {
               
                ConnectRemoteServer(textBox1.Text, comboBox1server.Text);
                this.listBoxbrowers.Items.Clear();
                oPCBrowser = opcserver.CreateBrowser(); 
                oPCBrowser.ShowBranches();
                oPCBrowser.ShowLeafs(true);         //展示节点
                foreach (var item in oPCBrowser)
                {
                    if (!this.listBoxbrowers.Items.Contains(item))        //清除重复的
                    {
                        this.listBoxbrowers.Items.Add(item.ToString());
                    }
                }
                oPCGroups = opcserver.OPCGroups;
                oPCGroups.DefaultGroupDeadband = 0;
                oPCGroups.DefaultGroupIsActive = true;
                oPCGroups.DefaultGroupUpdateRate = 200;    //刷新频率
                oPCGroup = oPCGroups.Add("wzw");
                oPCGroup.IsActive = true;
                oPCGroup.IsSubscribed = true; //异步回调
                oPCItems = oPCGroup.OPCItems;
                oPCGroup.DataChange += OPCGroup_DataChange;
                    


            }
            catch 
            
            {
                MessageBox.Show("连接失败，请重试");
            }
        }
        public static void write_log_txt(string str)           //写入TXT
        {
            try
            {
                string file_str = @"../../Log/" + "log".Trim() + "_".Trim() + DateTime.Now.ToString("yyyy-MM-dd").Trim() + ".txt";
                StreamWriter sw = File.AppendText(file_str);
                sw.Write(DateTime.Now.ToString() + ":");
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
            }
            catch
            {
                write_log_txt("写日志文件异常，write_log_txt(string str)!");
            }
        }
        private void OPCGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            //throw new NotImplementedException(); 上方 行动代码 数 句柄 数据 连接质量 时间戳
            for (int i=0;i<NumItems;i++)
            {
                serverhandle = Convert.ToInt32(ClientHandles.GetValue(i+1));
                OPCValueList[serverhandle-1].Value=ItemValues.GetValue(i+1).ToString();
                OPCValueList[serverhandle-1].Time = Convert.ToDateTime(TimeStamps.GetValue(i+1));
                this.dataGridViewvalue.DataSource = null;
                this.dataGridViewvalue.DataSource = OPCValueList;
                write_log_txt(ItemValues.GetValue(i + 1).ToString());
                string sql1 = "insert into opc(time,datas) values( '" + Convert.ToDateTime(TimeStamps.GetValue(i + 1)) + "','" + ItemValues.GetValue(i + 1).ToString() + "' )";
                MySqlCommand cmd1 = new MySqlCommand(sql1, conn);
                sda = new MySqlDataAdapter();
                sda.SelectCommand = cmd1;
                ds = new DataSet();
                sda.Fill(ds, "cs");
            }
        }

        private void listBoxbrowers_DoubleClick(object sender, EventArgs e)
        {
            OPCValueList.Add(new ClassOpcdata());
            OPCValueList[count].Name = this.listBoxbrowers.Text.Trim();
            oPCItem = oPCItems.AddItem(this.listBoxbrowers.Text.Trim(), count + 1);
            opcitemslist.Add(oPCItem);
            count += 1;

        }

        private void buttondisconnect_Click(object sender, EventArgs e)
        {
            opcserver.Disconnect();
            Environment.Exit(0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
        
            form2.Owner = this;
            this.Hide();
            form2.Show();
        }
    }
}
